import { clearDgCacheApi } from '@/pages/AuditPaper/service';
import { getNestApiData } from '@/services/cpasRequest';
import { Col, Modal, Progress, Row } from 'antd';
import { useEffect, useState } from 'react';
import { useModel } from 'umi';
import FileChart from './components/file-chart';
import GroupPart from './components/group-part';
import ProjectMembers from './components/ProjectMembers';
import { getDataSize, getFileSize, getFileStat, getUserStat } from './components/service';
import SpaceChart from './components/space-chart';
import UserInfo from './components/user-info';
import './index.less';

const Home = () => {
  const { initialState } = useModel('@@initialState');
  const { dbname, zcbfid } = initialState?.curPart as API.CurPart;
  const { usercode, username } = initialState?.curUser as API.CurUser;
  const [fileData, setFileData] = useState([]);
  const [userData, setUserData] = useState<any>({ project_count: 0, user_count: 0, open_count: 0 });
  const [fileSize, setFileSize] = useState(0);
  const [dataSize, setDataSize] = useState(0);
  const [isShowOpen, setShowOpen] = useState<boolean>(false);
  const [percentNum, setPercentNum] = useState<any>(0);
  const [contentMsg, setContentMsg] = useState('');

  console.log(dbname, zcbfid, usercode, username);

  const initFileStat = async () => {
    const res = await getFileStat({ zcbfid: dbname });
    setFileData(
      res.map((item: any) => {
        return {
          date: item.EditDate,
          paper: item.dg_count,
          attachment: item.fj_count,
        };
      }),
    );
  };

  // 清空底稿缓存
  useEffect(() => {
    clearDgCacheApi()
      .then(() => {
        console.log('清空缓存成功');
      })
      .catch(() => {
        console.error('清空缓存失败');
      });
  }, []);

  const initUserStat = async () => {
    const res = await getUserStat({ dbname, username });
    setUserData(res[0]);
  };

  const initSizeStat = async () => {
    let dataSize = await getDataSize({ zcbfid: dbname });
    if (dataSize && dataSize.length > 0 && dataSize[0].size) {
      dataSize = dataSize[0].size;
      if (typeof dataSize === 'string') {
        dataSize = parseInt(dataSize);
      }
    } else {
      dataSize = 0;
    }
    setDataSize(dataSize);
    console.log(dataSize);
    let fileSize = await getFileSize({ zcbfid: dbname });
    if (fileSize && Object.keys(fileSize).length > 0 && fileSize.size) {
      fileSize = fileSize.size;
      if (typeof fileSize === 'string') {
        fileSize = parseInt(fileSize);
      }
    } else {
      fileSize = 0;
    }
    setFileSize(fileSize);
    // console.log(fileSize);
  };

  /**
   *
   */
  const getProjectDbStatePercent = async (params: any) => {
    try {
      const res = await getNestApiData('/getProjectDbState', 'get', params);
      if (res.ok) {
        return Promise.resolve({
          data: res.data,
          msg: res.msg,
          success: true,
        });
      }
      return Promise.resolve({
        data: res.data,
        msg: res.msg,
        success: false,
      });
    } catch (error) {
      return Promise.resolve({
        data: '接口getProjectDbState出错了！',
        success: false,
      });
    }
  };

  const realModal = async () => {
    setContentMsg('');
    setPercentNum(0);
    const res = await getProjectDbStatePercent({
      dbname,
    });
    // 如果是 false  就调用进度条， 如果是true 就不要调用进度条逻辑了
    if (res?.data) {
      setShowOpen(false);
    } else {
      setShowOpen(true);
      fetch(`/cpasApi/checkProjectDbState?dbname=${dbname}`)
        .then((response) => {
          const reader = response.body?.getReader();
          function readChunk(): any {
            return reader?.read().then(({ value, done }) => {
              if (done) {
                console.log('100% 完成');
                setContentMsg('读取数据块完成');
                setPercentNum(100);
                setTimeout(() => {
                  setShowOpen(false);
                }, 200);
                return;
              }
              const chunk = new TextDecoder().decode(value);
              const a_chunk = chunk.split('\n');
              const { process } = JSON.parse(a_chunk[a_chunk.length - 2]);
              setPercentNum(process?.toFixed(2));
              console.log(process, '@@@');
              setContentMsg('继续读取下一个数据块...');
              // 继续读取下一个数据块
              return readChunk();
            });
          }
          return readChunk();
        })
        .catch((error) => {
          console.error('Error:', error);
          setContentMsg('读取数据块失败！');
          setTimeout(() => {
            setShowOpen(false);
          }, 200);
        });
    }
  };

  useEffect(() => {
    realModal();
    initFileStat();
    initUserStat();
    initSizeStat();
  }, []);

  return (
    <div className="dynamicHeight">
      <Row style={{ height: '55%' }}>
        <Col lg={18} md={24} style={{ borderBottom: '1px solid #d8d8d8' }}>
          <FileChart data={fileData} />
        </Col>
        <Col lg={6} md={24} style={{ borderLeft: '1px solid #d8d8d8' }}>
          <UserInfo
            username={username}
            editTzflCount={userData?.edit_tzfl_count ?? 0}
            tzflCount={userData?.tzfl_count ?? 0}
            editDgCount={userData?.edit_dg_count ?? 0}
            dgCount={userData?.dg_count ?? 0}
            editFjCount={userData?.edit_fj_count ?? 0}
            fjCount={userData?.fj_count ?? 0}
            // projectCount={userData.edit_tzfl_count + " / " + userData.tzfl_count}
            // userCount={userData.edit_dg_count + " / " + userData.dg_count}
            // openCount={userData.edit_fj_count + " / " + userData.fj_count}
          />
        </Col>
      </Row>
      <Row style={{ height: '45%' }}>
        <Col lg={12} md={24}>
          <GroupPart />
        </Col>
        <Col lg={6} md={24} style={{ height: '100%' }}>
          <SpaceChart dataSpace={dataSize} fileSpace={fileSize} />
        </Col>
        <Col lg={6} md={24} style={{ backgroundColor: '#fff', borderLeft: '1px solid #d8d8d8' }}>
          <ProjectMembers />
        </Col>
      </Row>

      <Modal
        open={isShowOpen}
        footer={null}
        centered
        maskClosable={false}
        closable={false}
        title={null}
        bodyStyle={{ background: 'none' }}
        // style={{ height: "200px" }}
        className="dot-body"
        wrapClassName="spin-example"
      >
        <Progress percent={percentNum} status="active" style={{ color: '#fff' }} />
        <div className="process-content">{contentMsg}</div>
      </Modal>
    </div>
  );
};

export default Home;
